import { useState, useEffect } from "react";
import { Image } from "antd";
import styles from "./AddProductManage.module.css";  // 复用添加产品的样式

interface EditProductManageProps {
    onClose?: () => void;
    onSuccess?: () => void;
    productData: {
        id: number;
        team: string;
        img: string;
        typeof: string;
        productName: string;
        sku: string;
    };
}

const EditProductManage = ({ onClose = () => {}, onSuccess = () => {}, productData }: EditProductManageProps) => {
    const [formData, setFormData] = useState(productData);
    const [selectedFile, setSelectedFile] = useState<File | null>(null);
    
    // 处理无效的图片路径
    const getValidImagePath = (imgPath: string) => {
        if (!imgPath || imgPath === 'string' || imgPath === '' || imgPath === 'null' || imgPath === 'undefined') {
            return null;
        }
        return imgPath;
    };
    
    const [imagePreview, setImagePreview] = useState<string | null>(getValidImagePath(productData.img));
    const [isUploading, setIsUploading] = useState(false);

    const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
        const files = e.target.files;
        if (!files || files.length === 0) return;

        const file = files[0];
        setSelectedFile(file);

        // 先显示本地预览
        const localPreviewUrl = URL.createObjectURL(file);
        setImagePreview(localPreviewUrl);

        // 立即上传文件
        await uploadFile(file);
    };

    const uploadFile = async (file: File) => {
        if (isUploading) return;

        setIsUploading(true);
        const uploadFormData = new FormData();
        uploadFormData.append('file', file);

        try {
            const response = await fetch('http://localhost:5233/api/Uplod/UplodFile', {
                method: 'POST',
                body: uploadFormData,
            });

            if (!response.ok) {
                throw new Error('图片上传失败');
            }

            const filePath = await response.text();

            // 更新表单数据中的图片路径
            setFormData(prev => ({
                ...prev,
                img: filePath
            }));

            // 更新预览图片
            setImagePreview(filePath);

        } catch (error) {
            alert('图片上传失败，请重试');
            // 恢复原图片（使用有效的路径）
            setImagePreview(getValidImagePath(productData.img));
            setSelectedFile(null);
        } finally {
            setIsUploading(false);
        }
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        // 确保所有必填字段都已填写
        if (!formData.team || !formData.typeof || !formData.productName || !formData.sku) {
            alert('请填写所有必填字段');
            return;
        }

        try {
            const response = await fetch('http://localhost:5233/api/ProductManage/UpdateProductManage', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(formData),
            });

            const result = await response.json();

            if (result.code === 200) {
                // 清理资源
                if (imagePreview && imagePreview.startsWith('blob:')) {
                    URL.revokeObjectURL(imagePreview);
                }
                setSelectedFile(null);
                
                alert('更新成功');
                // 确保先调用 onSuccess 再关闭弹窗
                onSuccess();
                onClose();
            } else {
                throw new Error(result.message || '更新失败');
            }
        } catch (error) {
            alert('更新产品失败，请重试');
        }
    };

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: value
        }));
    };

    // 组件卸载时清理资源
    useEffect(() => {
        return () => {
            if (imagePreview && imagePreview.startsWith('blob:')) {
                URL.revokeObjectURL(imagePreview);
            }
        };
    }, []);

    return (
        <div className={styles.addProductForm}>
            <div className={styles.header}>
                <h3>编辑产品</h3>
                <button onClick={onClose} className={styles.closeButton}>×</button>
            </div>
            <form onSubmit={handleSubmit}>
                <div className={styles.formGroup}>
                    <label className={styles.required}>产品团队</label>
                    <input
                        type="text"
                        name="team"
                        value={formData.team}
                        onChange={handleChange}
                        required
                        placeholder="请输入产品团队"
                    />
                </div>
                <div className={styles.formGroup}>
                    <label>产品图片</label>
                    <div className={styles.imageUploadContainer}>
                        <div className={styles.uploadBox}>
                            <input
                                type="file"
                                accept="image/*"
                                onChange={handleImageUpload}
                                className={styles.fileInput}
                                id="editFileInput"
                                disabled={isUploading}
                            />
                            <label htmlFor="editFileInput" className={styles.uploadLabel}>
                                {isUploading ? '上传中...' : '选择新图片'}
                            </label>
                        </div>
                        {imagePreview && (
                            <div className={styles.imagePreview}>
                                <Image
                                    src={imagePreview}
                                    alt="预览图"
                                    width={120}
                                    height={120}
                                    preview={false}
                                    onError={(e) => {
                                        const target = e.currentTarget as HTMLImageElement;
                                        target.parentElement!.innerHTML = 
                                            '<div style="padding: 20px; text-align: center; color: #999; border: 1px dashed #ddd;">图片加载失败</div>';
                                    }}
                                />
                            </div>
                        )}
                    </div>
                </div>
                <div className={styles.formGroup}>
                    <label className={styles.required}>产品类型</label>
                    <input
                        type="text"
                        name="typeof"
                        value={formData.typeof}
                        onChange={handleChange}
                        required
                        placeholder="请输入产品类型"
                    />
                </div>
                <div className={styles.formGroup}>
                    <label className={styles.required}>产品名称</label>
                    <input
                        type="text"
                        name="productName"
                        value={formData.productName}
                        onChange={handleChange}
                        required
                        placeholder="请输入产品名称"
                    />
                </div>
                <div className={styles.formGroup}>
                    <label className={styles.required}>产品SKU</label>
                    <input
                        type="text"
                        name="sku"
                        value={formData.sku}
                        onChange={handleChange}
                        required
                        placeholder="请输入产品SKU"
                    />
                </div>
                <div className={styles.formActions}>
                    <button type="submit" className={styles.submitButton} disabled={isUploading}>
                        确认更新
                    </button>
                    <button 
                        type="button" 
                        onClick={onClose} 
                        className={styles.cancelButton}
                    >
                        取消
                    </button>
                </div>
            </form>
        </div>
    );
};

export default EditProductManage; 